import { PageContainer } from '@ant-design/pro-layout';
import React, { useRef } from 'react';
import ProForm, { ModalForm, ProFormText } from '@ant-design/pro-form';
import { Button, message } from 'antd';
import { WaterMark } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable, { TableDropdown } from '@ant-design/pro-table';
import { request } from 'umi';
import { PlusOutlined, AlertOutlined, DeleteOutlined } from '@ant-design/icons';
import { api } from '@/global';
import { useAccess, Access } from 'umi';
type DeptItem = {
  id: number;
  deptName: string;
  deptNumber: number;
  createTime: string;
  updateTime: string;
  professionalNumber: number;
};

export default () => {
  const actionRef = useRef<ActionType>();
  const access = useAccess();
  const columns: ProColumns<DeptItem>[] = [
    {
      dataIndex: 'id',
      valueType: 'indexBorder',
      width: 48,
    },
    {
      title: '系别名称',
      dataIndex: 'deptName',
      copyable: true,
    },
    {
      title: '系统内该系人数',
      dataIndex: 'deptNumber',
      filters: true,

      sorter: (a, b) => a.deptNumber - b.deptNumber,
      search: false,
    },
    {
      title: '所含专业数',
      dataIndex: 'professionalNumber',
      filters: true,

      sorter: (a, b) => a.professionalNumber - b.professionalNumber,
      search: false,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '最后一次修改时间',
      dataIndex: 'updateTime',
      search: false,
      valueType: 'dateTime',
    },
    {
      title: '操作',
      valueType: 'option',
      render: (text, record, _, action) => [
        <Access key={'update' + record.id} accessible={access.normalButtonFilter('DEPT:UPDATE')}>
          <ModalForm
            title="修改数据"
            key="id"
            autoFocusFirstInput
            modalProps={{
              destroyOnClose: true,
              onCancel: () => console.log('run'),
            }}
            onFinish={async (values) => {
              values.id = record?.id;
              const result = await request(api.insertOrUpdateDept, {
                method: 'POST',
                data: values,
              });

              if (result.success) {
                message.info('修改成功');
                actionRef.current?.reload();
                return true;
              } else {
                message.error('修改失败,请联系管理员');
                return false;
              }
            }}
            trigger={
              <Button title="新增系别" type="primary">
                <AlertOutlined />
                修改
              </Button>
            }
          >
            <ProFormText
              initialValue={record?.deptName}
              width="sm"
              name="deptName"
              label="系别名称"
              rules={[
                {
                  required: true,
                  message: '请输入系部名称',
                },
              ]}
            />
          </ModalForm>
        </Access>,
        <Access key={'delete' + record.id} accessible={access.normalButtonFilter('DEPT:DELETE')}>
          <ModalForm
            key="id"
            title="删除系部"
            trigger={
              <Button type="danger">
                <DeleteOutlined />
                删除
              </Button>
            }
            submitter={{
              resetButtonProps: {
                type: 'dashed',
              },
            }}
            onFinish={async (values) => {
              const result = await request(
                api.deleteDeptById,

                {
                  method: 'POST',
                  data: {
                    id: record?.id,
                  },
                  skipErrorHandler: true,
                },
              ).catch((e) => {
                if (e.response.status === 500) {
                  message.error('该系部下面有用户或者专业存在');
                }
                return true;
              });

              if (result.success) {
                message.info('删除成功');
                actionRef.current?.reload();
                return true;
              } else {
                message.error('删除失败');
                return true;
              }
            }}
          >
            是否删除&nbsp;&nbsp;
            <span style={{ fontWeight: 900, fontSize: 25, color: '#3498db' }}>
              {record?.deptName}
            </span>
            &nbsp;&nbsp;
          </ModalForm>
        </Access>,
      ],
    },
  ];
  return (
    <PageContainer
      waterMarkProps={{ content: '山西工程技术学院' }}
      header={{
        title: '系别管理',
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织管理',
            },
            {
              path: '',
              breadcrumbName: '系别管理',
            },
          ],
        },
      }}
    >
      <ProTable<DeptItem>
        columns={columns}
        actionRef={actionRef}
        request={async (params = {}, sort, filter) => {
          console.log(sort, filter);
          return request<{
            data: DeptItem[];
          }>(api.getDeptList, {
            method: 'POST',
            data: {
              ...params,
            },
          });
        }}
        editable={{
          type: 'multiple',
        }}
        columnsState={{
          persistenceKey: 'pro-table-singe-demos',
          persistenceType: 'localStorage',
        }}
        rowKey="id"
        search={{
          labelWidth: 'auto',
        }}
        form={{
          // 由于配置了 transform，提交的参与与定义的不同这里需要转化一下
          syncToUrl: (values, type) => {
            if (type === 'get') {
              return {
                ...values,
                created_at: [values.startTime, values.endTime],
              };
            }
            return values;
          },
        }}
        pagination={{
          pageSize: 5,
        }}
        dateFormatter="string"
        headerTitle="系部信息"
        toolBarRender={(_, b) => [
          <Access key="insert" accessible={access.normalButtonFilter('DEPT:INSERT')}>
            <ModalForm
              title="新增系别"
              key="id"
              autoFocusFirstInput
              modalProps={{
                destroyOnClose: true,
                onCancel: () => console.log('run'),
              }}
              onFinish={async (values) => {
                const result = await request(api.insertOrUpdateDept, {
                  method: 'POST',
                  data: values,
                });

                if (result.success) {
                  message.info('添加成功');
                  actionRef.current?.reload();
                  return true;
                } else {
                  message.error('添加失败,请联系管理员');
                  return false;
                }
              }}
              trigger={
                <Button title="新增系别" type="primary">
                  <PlusOutlined />
                  新增系别
                </Button>
              }
            >
              <ProFormText
                width="sm"
                name="deptName"
                label="系别名称"
                rules={[
                  {
                    required: true,
                    message: '请输入系部名称',
                  },
                ]}
              />
            </ModalForm>
          </Access>,
        ]}
      />
    </PageContainer>
  );
};
